package com.ahaoyou.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Author LH
 * @create 2021/12/22 18:07
 */
@Configuration
public class EsConfig {

    @Value("${elasticsearch.hosts}")
    private String hosts;

    /**
     * scheme 类型
     */
    @Value("${elasticsearch.scheme}")
    private String scheme;

    //创建 RestHighLevelClient
    @Bean
    public RestHighLevelClient client() {
        String[] split = hosts.split(",");
        //读取配置文件中的端口号
        HttpHost[] httpHosts = new HttpHost[split.length];
        int index = 0;
        for (String host : split) {
            String[] httHost = host.split(":");
            httpHosts[index++] = new HttpHost(httHost[0], Integer.parseInt(httHost[1]), scheme);
        }
       /* 设置es用户名密码
       final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(
                AuthScope.ANY, new UsernamePasswordCredentials(userName, password));*/
        RestClientBuilder builder = RestClient.builder(httpHosts);
//      builder.setHttpClientConfigCallback(f -> f.setDefaultCredentialsProvider(credentialsProvider));
        return new RestHighLevelClient(builder);
    }

}
